<script>
import config from './utils/config.js';
import { reportAddress, getLocalInfo } from './utils/global_fucs.js';
import wxNetwork from './utils//wx_network.js';
import {
	hanleToken,
	uniqueArr
} from '@/utils/utils.js';
import { getOfRule } from '@/apis/user.js';

require('./utils/webmonitor.mp.min');
// 
// 初始化用户信息
// @param userId 用户唯一性标识 (手机号、用户名、id等)
// @param userTag 用于区分同一个项目下，角色的分类（公司A, B, C, D等）
// @param projectVersion 应用每次发布的版本号
// 
uni.setStorageSync('wmUserInfo', JSON.stringify({ userId: 'userId1', userTag: 'A', projectVersion: '1.0.1', env: 'pro' }));
import { mapState, mapActions } from 'vuex';
export default {
	globalData: {
		// 相机模型情况
		SIDA: null,
		Module: null,
		// 0 未初始化， 1初始化成功 2加载失败 
		modelStatus: 0,

		networkStatus: '',// 网络状态 offline poor normal
		onlineStatus: uni.getStorageSync('onlineStatus') === '' ? true : uni.getStorageSync('onlineStatus'),// false 为离线模式
		localListen: false,// 定位是否监听中
		cameraAuth: false,// 相机权限 
		userinfo: {},
		appName: config.appName,
		// 登录后跳转的链接
		reUrl: '',
		fristUserId: '',
		schoolId: '0',
		token: '',
		refresh_token: '',
		localinfo: {

		},
		// 首页是否加载
		indexLauch: false,
		isConnected: true,
		seed: 10,
		// 是否救援中 
		rescueIng: false,

		wsServer: null,
		deviceIds: [],

		// 定位上报配置
		addressSetting: {
			// 上报开始时间(不在区间内不上报
			gpsBegeinTime: '',
			// 上报结束时间
			gpsEndTime: '',
			// 上报频率（分钟
			gpsAddFrequency: '',
		},
		lastSyncOrder: {
			id: '',
			time: ''
		}

	},
	watch: {
		 
	},
	computed: {
		...mapState('user', ['userinfo']), 
	},
	methods: {
		...mapActions('user', ['handleRreshToken', 'getRoutes'])
	},
	onError: function (err) {
	},
	onLaunch: function () {
		console.log('App Launch:', uni.getStorageSync('onlineStatus') === '');

		uni.$on('networkChange', (res) => {
			// 监听网络状态
			// console.log('网络状态更变：', res, this.globalData.onlineStatus)
			this.globalData.networkStatus = res;
		});

		uni.$on('onlineStatusChange', (res) => {
			// 离线在线切换
			console.log('离线在线切换', res, this.globalData.onlineStatus);
			uni.setStorageSync('onlineStatus', res);
			this.$store.commit('system/setOnlineStatus', this.globalData.onlineStatus);
		});

		uni.getNetworkType({
			success(res) {
				wxNetwork.on(res);
			},
			fail(err) {
				wxNetwork.on({});
			}
		});
		if (hanleToken('get', 'token')) {
			setTimeout(() => {
				this.getRoutes();
				// 更新定位上报配置
				getOfRule().then(res => {
					console.log('getOfRule', res);
					if (res.data && res.data.gpsAddFrequency) {
						this.globalData.seed = res.data.gpsAddFrequency * 60;
					} else {
						this.globalData.seed = 60;
					}
					this.globalData.addressSetting = res.data || {
						gpsBegeinTime: '',
						// 上报结束时间
						gpsEndTime: '',
						// 上报频率（分钟
						gpsAddFrequency: '',
					};
					uni.setStorage({
						key: 'addressSetting',
						data: res.data || {}
					});
				}).catch(() => {
					this.globalData.seed = 60;
				});
			}, 500);
		}
		// 网络变化触发事件
		uni.onNetworkStatusChange((res) => {
			// 取反满足条件,跳转已经写好的网络异常页面
			// console.log('onNetworkStatusChange', res)
			getApp().globalData.isConnected = res.isConnected;
			wxNetwork.on({});
		});

		// 定时上报定位

		// #ifndef H5
		setInterval(async () => {
			if (this.globalData.seed <= 0) {// 定位上报，每隔60秒
				const gpsAddFrequency = this.globalData.addressSetting.gpsAddFrequency ? this.globalData.addressSetting.gpsAddFrequency * 60 : 60;// 上报间隔
			 
				if (this.userinfo.user_id && this.$config.addressTimer) {
					if ( this.globalData.addressSetting && this.globalData.addressSetting.gpsBegeinTime && this.globalData.addressSetting.gpsEndTime) {
						// 获取今天的日期对象
						const today = new Date();

						// 获取今天的时分秒（注意：获取小时、分钟、秒数）
						const currentHours = today.getHours();
						const currentMinutes = today.getMinutes();
						const currentSeconds = today.getSeconds();

						// 时间区间的开始时间和结束时间（只取时分秒部分）
						const startTime = this.globalData.addressSetting.gpsBegeinTime.split(' ')[1];
						const endTime = this.globalData.addressSetting.gpsEndTime.split(' ')[1];

						// 转换时间区间为小时、分钟、秒
						const [startHours, startMinutes, startSeconds] = startTime.split(':').map(Number);
						const [endHours, endMinutes, endSeconds] = endTime.split(':').map(Number);

						// 判断当前时间是否在区间内
						const isInRange =
							(currentHours > startHours || (currentHours === startHours && currentMinutes > startMinutes) ||
								(currentHours === startHours && currentMinutes === startMinutes && currentSeconds >= startSeconds)) &&
							(currentHours < endHours || (currentHours === endHours && currentMinutes < endMinutes) ||
								(currentHours === endHours && currentMinutes === endMinutes && currentSeconds <= endSeconds));
						if (!isInRange) {
							// 当前时间不在上报区间范围内（不上报
							console.log('不在时间区间');
							this.globalData.seed = gpsAddFrequency;
							return;
						}
					}
					let local = await getLocalInfo();
					if (local.longitude) {
						console.log('上报');
						reportAddress({
							longitude: local.longitude,
							latitude: local.latitude,
							userId: this.userinfo.user_id,
							operation: 0,
							recordType: 2// 日常定位
						});
					} else {
						console.log('地址获取失败');
					}
				}
				this.globalData.seed = gpsAddFrequency;
				// this.globalData.seed = this.globalData.rescueIng == true && this.globalData.localinfo.onChange == true ? 10 : 60;// 重置倒计时60秒 救援中10秒
			}

			this.globalData.seed--;
			// console.log('全局定时器', this.globalData.seed, this.globalData.addressSetting);
		}, 1 * 1000);
		// #endif

		// #ifdef H5 
		setTimeout(() => {
			if (this.$config.addressTimer && window.sida) {
				window.sida.startReportLocal({
					operation: 0,
					recordType: 2// 日常定位
				});
			}
		}, 1000);
		// #endif

		// user info refresh
		this.$store.dispatch('user/getUserInfo');
	},

	onShow: function () {
		if (uni.canIUse('getUpdateManager')) {
			const updateManager = uni.getUpdateManager();
			updateManager.onCheckForUpdate(function (res) {
				console.log('App Show', res);
				if (res.hasUpdate) {
					updateManager.onUpdateReady(function () {
						uni.hideLoading();
						uni.showModal({
							title: '更新提示',
							content: '新版本已经准备好，是否重启应用？',
							success: function (res) {
								if (res.confirm) {
									updateManager.applyUpdate();
								}
							}
						});
					});
					updateManager.onUpdateFailed(function () {
						uni.showModal({
							title: '已经有新版本了哟~',
							content: '新版本已经上线啦~，请您删除当前应用程序，重新搜索打开哟~'
						});
					});
				}
			});
		} else {
			uni.showModal({
				title: '提示',
				content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
			});
		}
		// #ifdef H5
		if (window.sida) {
			const vm = this;
			window.sida.setGeoFenceReceiver({
				callback: async function (fenceStatusList) {
					if (fenceStatusList && fenceStatusList.length > 0) {
						let fenceArr = fenceStatusList.map(item => {
							return {
								...item,
								planId: item.id.split('|')[0],
								buildingId: item.id.split('|')[1],
								elevatorId: (item.id.split('|')[2] || '').split('-')[0],
								buildingPlanCounts: item.id.split('-')[1],// 项目工单数量
								signType: item.id.split('-')[2]// 签到状态
							};
						});
						let dataList = vm.$store.state.user.dataList;
						let statusObj = {};
						let statusInArr = [];
						let statusOutArr = [];
						fenceArr.forEach(item => {// 查找对应围栏数据
							dataList.forEach(item1 => {
								if (item.buildingId === item1.buildingId) {
									statusObj = item;
								}
								if (item.buildingId === item1.buildingId && item.state === 'STATUS_IN') {
									statusInArr.push(item1);
								}
								if (item.buildingId === item1.buildingId && item.state === 'STATUS_OUT') {
									statusOutArr.push(item1);
								}
							});
						});
						let multipleArr = uniqueArr(statusInArr, 'buildingId');// 去重
						// let statusOutList = uniqueArr(statusOutArr, 'buildingId');// 去重
						hanleToken('set', 'enclosureData', multipleArr);// 用于多个围栏项目重叠 去多个签到弹窗获取数据

						if (statusOutArr && statusOutArr.length > 0) {// 存在出围栏数据 有签退工单跳转单个签退弹窗
							let statusOutObj = statusOutArr.find((item) => item.signType == 2) || {};
							if (Object.keys(statusOutObj).length > 0) {
								uni.navigateTo({
									url: '/subpages/repair/repariDetail?planId=' + statusOutObj.planId + '&elevatorId=' + statusOutObj.elevatorId + '&state=' + 'STATUS_OUT',
								});
								return;
							}
						}
						// if(fenceArr && fenceArr.length === 1){//单个项目 存在多个工单 有签退工单 跳转单个签退弹窗
						// 	let multipleObj = dataList.find((item)=>item.signType == 2) || {};
						// 	if(Object.keys(multipleObj).length > 0){
						// 		uni.navigateTo({
						// 			url: '/subpages/repair/repariDetail?planId=' + multipleObj.planId + '&elevatorId=' + multipleObj.elevatorId + '&state=' + 'STATUS_OUT',
						// 		});
						// 		return;
						// 	}
						// }
						if (multipleArr && multipleArr.length > 1) {// 存在重叠项目 跳转到多个签到弹窗
							uni.navigateTo({
								url: '/subpages/workOrders/records?type=2&state=STATUS_IN' + '&buildingId=' + statusObj.buildingId + '&elevatorId=' + statusObj.elevatorId + '&planId=' + statusObj.planId,
							});
							return;
						}

						if (statusObj.buildingPlanCounts == 1) {// 只有一个维修工单 跳转单个签到弹窗
							if (statusObj.state === 'STATUS_IN' && statusObj.signType == '1') {
								uni.navigateTo({
									url: '/subpages/repair/repariDetail?planId=' + statusObj.planId + '&elevatorId=' + statusObj.elevatorId + '&state=' + 'STATUS_IN',
								});
							}
							if (statusObj.state === 'STATUS_OUT' && statusObj.signType == '2') {
								uni.navigateTo({
									url: '/subpages/repair/repariDetail?planId=' + statusObj.planId + '&elevatorId=' + statusObj.elevatorId + '&state=' + 'STATUS_OUT',
								});
							}
						}

						if (statusObj.buildingPlanCounts > 1) {// 没有重叠项目且有多个维修工单 
							if (statusObj.state === 'STATUS_IN') {// 跳转多个签到弹窗
								uni.navigateTo({
									url: '/subpages/workOrders/records?type=2&state=STATUS_IN' + '&buildingId=' + statusObj.buildingId + '&elevatorId=' + statusObj.elevatorId + '&planId=' + statusObj.planId,
								});
							}
						}
					}
				}
			});
		} else {
			console.error('sida 包未加载，请确保已引入 sida 相关脚本');
		}
		// #endif
	},
	onHide: function () {
		console.log('App Hide');
	},
};
</script>

<style>

page {
	font-size: 28rpx;
	/* letter-spacing: 1rpx; */
}

.beTwoLine {
	text-overflow: -o-ellipsis-lastline;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	line-clamp: 2;
	-webkit-box-orient: vertical;
}

.beOneLine {
	white-space: nowrap;
	text-overflow: ellipsis;
	overflow: hidden;
	word-break: break-all;
}

.flex {
	display: flex;
	align-items: center;
	justify-content: center;
}

.wx-progress-inner-bar {
	border-radius: 10px;
	box-shadow: 0px 2px 2px 0px rgba(0, 135, 238, 0.34);
}

button::after {
	border: none;
}

button {
	background-color: #fff;
	padding: 0;
	width: 100%;
	font-size: 28rpx;
	/* width: 238rpx; */
	/* height: 72rpx; */
	display: flex;
	align-items: center;
	justify-content: center;
	background: #0091ff;
	border-radius: 8rpx;
	color: #fff;
}

.empty {
	height: 170rpx;
	color: #ccc;
}

uni-modal {
	z-index: 19999 !important;
}

/*  #ifdef H5  */
::v-deep .uni-input-input[disabled] {
	pointer-events: none !important; 
}
/*  #endif  */

</style>
